import React, { useEffect, useState } from 'react'
import { Button, Input, Modal, Table } from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import { nanoid } from 'nanoid'

function Add(props) {
  const columns = [
    {
      title: '账号',
      dataIndex: 'username',
      key: 'username',
      render: (text, record) => (
        <div>
          <Input
            onChange={(e) => {
              changeValue(record, e.target.value, 'username')
            }}
          />
        </div>
      )
    },
    {
      title: '密码',
      dataIndex: 'password',
      key: 'password',
      width: 150,
      render: (text, record) => (
        <div>
          <Input
            onChange={(e) => {
              changeValue(record, e.target.value, 'password')
            }}
          />
        </div>
      )
    },
    {
      title: '备注', dataIndex: 'tip', key: 'tip',
      render: (text, record) => (
        <div>
          <Input
            onChange={(e) => {
              changeValue(record, e.target.value, 'tip')
            }}
          />
        </div>
      )
    },
    {
      title: '操作',
      key: 'action',
      width: 80,
      render: (text, record) => (
        <div>
          <Button
            type={'link'}
            danger
            onClick={() => {
              remove(record)
            }}
          >
            删除
          </Button>
        </div>
      )
    }
  ]

  const [data, setData] = useState([
    {
      key: nanoid(),
      username: '',
      password: '',
      tip: ''
    }
  ])

  function changeValue(record, value, label) {
    setData(data.map(item => {
      if (item.key === record.key) {
        item[label] = value
      }
      return item
    }))
  }

  function add() {
    setData([...data, {
      key: nanoid(),
      username: '',
      password: '',
      tip: ''
    }
    ])
  }

  function remove(record) {
    console.log(record.key, data)
    setData(data.filter(item => item.key !== record.key))
  }

  function close() {
    props.onCancel()
    setData([{ key: nanoid(), username: null, password: '', tip: '' }])
  }

  function save() {
    props.onSave(data)
  }

  useEffect(() => {
    if (!props.visible) {
      close()
    }
  }, [props.visible])
  return (
    <Modal open={props.visible} onCancel={() => close()} title={'添加'} width={600} onOk={save}>
      <Table columns={columns} dataSource={data} pagination={{ position: ['none'] }}></Table>
      <div className={'mt-4 text-center'}>
        <Button onClick={add}><PlusOutlined /></Button>
      </div>
    </Modal>
  )
}

export default Add
